<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 300px"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import {
  onBeforeUnmount,
  ref,
  shallowRef,
  onMounted,
  watch,
  reactive,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
// 引入自定义请求库
import { postAction } from "@/utils/system/commonUse";
//
import { ElMessageBox, ElMessage } from "element-plus";
import axios from "axios";

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");
// watch(valueHtml, () => {
//   console.log(valueHtml);
// });

const mode = ref("default");

// 模拟 ajax 异步获取内容
onMounted(() => {
  getList();
});

const toolbarConfig = {};
let editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {},
  },
};
editorConfig.MENU_CONF["uploadImage"] = {
  fieldName: "uploadFile",
  meta: {
    id: sessionStorage.getItem("id"),
    typeStr: "1002",
  },
  server: "http://47.96.231.238:8112/upload/uploadFile",
};

const getList = () => {
  postAction(`${url.getList}/${sessionStorage.getItem("id")}`)
    .then((data: any) => {
      console.log("data===>", data);
      valueHtml.value = data.data.announcementTransfer;
      // if (data.code != 1000) {
      //   return ElMessage.error(data.msg);
      // }
      // ElMessage.success(data.msg);
    })
    .catch((err) => {
      console.log(err);
      // ElMessage.error("表格数据获取失败");
    });
};

const obj = reactive({
  id: sessionStorage.getItem("id"),
  announcementTransfer: valueHtml,
  typeStr: "1",
});

const url = reactive({
  saveEditorUrl: "/project/saveOrUpdate",
  getList: "/project/getById",
});
defineExpose({
  valueHtml,
});

const cliTest = () => {
  postAction(url.saveEditorUrl, obj)
    .then((data: any) => {
      if (data.code != 1000) {
        return ElMessage.error(data.msg);
      }
      console.log(data);
    })
    .catch((err) => {
      console.log(err);
    });
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  console.log("editor", editor);

  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style lang="scss" scoped></style>
